package com.enjoyor.soa.traffic.frame.refresh;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.scope.refresh.RefreshScope;
import org.springframework.stereotype.Component;

import com.ctrip.framework.apollo.model.ConfigChange;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import com.enjoyor.soa.traffic.frame.configure.RedisConfig;
import com.enjoyor.soa.traffic.frame.configure.Swagger2Config;

@Component
public class ApolloConfigRefresh {

    @Autowired
    private Swagger2Config Swagger2Config;

    @Autowired
    private RedisConfig redisConfig;

    @Resource
    private RefreshScope refreshScope;

    @ApolloConfigChangeListener(value = { "application", "swagger2", "log4j" })
    private void onChange(ConfigChangeEvent changeEvent) {
        boolean swagger2CacheKeysChanged = false;
        boolean redisCacheKeysChanged = false;
        for (String key : changeEvent.changedKeys()) {
            if (key.startsWith("swagger2")) {
                ConfigChange change = changeEvent.getChange(key);
                System.out.println(String.format(
                        "Found JavaConfigSample change - key: %s, oldValue: %s, newValue: %s, changeType: %s",
                        change.getPropertyName(), change.getOldValue(), change.getNewValue(), change.getChangeType()));
                swagger2CacheKeysChanged = true;
                break;
            }
            if (key.startsWith("spring.redis")) {
                redisCacheKeysChanged = true;
                break;
            }
        }

        if (swagger2CacheKeysChanged) {
            // refreshScope.refresh("basePackage");
            refreshScope.refresh("apiInfo");
            // refreshScope.refreshAll();
            // refreshScope.refresh("docket1");
            System.out.println(Swagger2Config.toString());
        }

        if (redisCacheKeysChanged) {
            // refreshScope.refresh("jedisConnectionFactory");
            //refreshScope.refresh("redisDatabase");
            refreshScope.refresh("jedisPoolConfig");
            System.out.println(redisConfig.toString());
        }

    }

}
